#include "gd32f30x.h"                   // Device header
#include "main.h"

void Task1(void * param);
void Task2(void * param);
void CreateOSTask(void);

QueueSetHandle_t keyQueSet = NULL;//按键队列集
TaskHandle_t xKeyPressedTaskTCB = NULL;//多按键处理任务

QueueHandle_t pxUpKeyPressedSemephore = NULL;//上键按下信号量
QueueHandle_t pxDownKeyPressedSemephore = NULL;//下键按下信号量
QueueHandle_t pxLeftPressedSemephore = NULL;//左键按下信号量
QueueHandle_t pxRightPressedSemephore = NULL;//右键按下信号量

void KeyPressedHandler(void * param);

int main(void)
{
  systemClockConfig();
  systick_config();
  CreateOSTask();
  vTaskStartScheduler();
  while(1)
  {

  }
}

void CreateOSTask(void)
{ 
  pxUpKeyPressedSemephore = xSemaphoreCreateBinary();
  pxDownKeyPressedSemephore = xSemaphoreCreateBinary();
  pxLeftPressedSemephore = xSemaphoreCreateBinary();
  pxRightPressedSemephore = xSemaphoreCreateBinary();

  xTaskCreate(KeyPressedHandler,"KeyPressedHandler",256,NULL,20,&xKeyPressedTaskTCB);
}

void KeyPressedHandler(void * param)
{
  keyQueSet = xQueueCreateSet(4);

  xQueueAddToSet(pxUpKeyPressedSemephore,keyQueSet);
  xQueueAddToSet(pxDownKeyPressedSemephore,keyQueSet);
  xQueueAddToSet(pxLeftPressedSemephore,keyQueSet);
  xQueueAddToSet(pxRightPressedSemephore,keyQueSet);
  QueueHandle_t pxQueue = NULL;
  while(1)
  {
    pxQueue = xQueueSelectFromSet(keyQueSet,portMAX_DELAY);
    
    if( pxQueue == pxUpKeyPressedSemephore )
    {
      xSemaphoreTake(keyQueSet,portMAX_DELAY);
      /*上键处理逻辑*/
    }
    else if( pxQueue == pxDownKeyPressedSemephore )
    {
      xSemaphoreTake(keyQueSet,0);
      /*下键处理逻辑*/      
    }
    else if( pxQueue == pxLeftPressedSemephore )
    {
      xSemaphoreTake(keyQueSet,0);
      /*左键处理逻辑*/      
    }
    else if( pxQueue == pxRightPressedSemephore )
    {
      xSemaphoreTake(keyQueSet,0);
      /*右键处理逻辑*/      
    }

    pxQueue = NULL;    
  }
}

void EXTI5_9_IRQHandler(void)
{
  if( SET == gpio_input_bit_get(GPIOA,GPIO_PIN_0) )
  {
    xSemaphoreGiveFromISR(pxUpKeyPressedSemephore,NULL);
  }
  if( SET == gpio_input_bit_get(GPIOA,GPIO_PIN_1) )
  {
    xSemaphoreGiveFromISR(pxDownKeyPressedSemephore,NULL);
  }
  if( SET == gpio_input_bit_get(GPIOA,GPIO_PIN_2) )
  {
    xSemaphoreGiveFromISR(pxLeftPressedSemephore,NULL);
  }
  if( SET == gpio_input_bit_get(GPIOA,GPIO_PIN_3) )
  {
    xSemaphoreGiveFromISR(pxRightPressedSemephore,NULL);
  }
}
